package com.time.hellotime.components.discovery;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.google.gson.Gson;
import com.time.hellotime.R;
import com.time.hellotime.app.AddressManager;
import com.time.hellotime.app.MyApplication;
import com.time.hellotime.base.BaseFragment;
import com.time.hellotime.common.event.BaseEvent;
import com.time.hellotime.components.WebDetailActivity;
import com.time.hellotime.components.banner.Banner;
import com.time.hellotime.components.banner.BannerConfig;
import com.time.hellotime.components.banner.listener.OnBannerListener;
import com.time.hellotime.components.discovery.city.CityListActivity;
import com.time.hellotime.servermodel.AppBanner;
import com.time.hellotime.servermodel.BasicBean;
import com.time.hellotime.servermodel.discovery.DiscoveryData;
import com.time.hellotime.utils.NetWorkUtils;
import com.time.hellotime.utils.ToastUtils;
import com.time.hellotime.webserver.helper.WebServerManager;
import com.time.hellotime.components.banner.loader.GlideImageLoader;
import com.time.hellotime.webserver.request.BasicRequest;
import com.time.hellotime.webserver.request.requestsParamters.DiscoveryParameters;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.rest.Request;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * 发现公益
 * Created by Bing on 2017/10/25.
 * E-mail is tx16bing@163.com
 */

public class DiscoveryFragment extends BaseFragment implements
        View.OnClickListener, AMapLocationListener {

    private static final int CITY_LIST_REQUEST_CODE = 102;

    public static final String detailUrl = new StringBuilder()
            .append(AddressManager.getInstance().getWebAddress())
            .append("/volunteer-activity-detail/")
            .append(MyApplication.getInstance().isLogin() ? MyApplication.getInstance().getAccount() : "-1")
            .append("/android/").toString();

    public static String CURRENT_CITY = "";
    private TextView tvCurCity, tvVolunteer;
    private Banner mBanner;
    private LinearLayout llOne, llTwo, llThree;
    private TextView tvCollection, tvExecution, tvOver;
    private View oneLine, twoLine, threeLine;
    private ViewPager mPager;

    private List<String> bannerImages = new ArrayList<>();
    private List<Fragment> fragments = new ArrayList<>();
    private CollectionFrag collectionFrag;
    private ExecutionFrag executionFrag;
    private OverFrag overFrag;

    // AMap
    private AMapLocationClient locationRequest;
    private double mLatitude, mLongitude;

    private Request request;
    private int DIS_BANNER_LIST_WHAT = 22;

    @Override
    public void initContentView(View contentView) {
        assignViews();
        initViewPager();
        andPermission();
        getDisBanners();
    }

    private void assignViews() {
        tvCurCity = findView(R.id.tv_dis_location);
        tvVolunteer = findView(R.id.tv_dis_volunteer);
        mBanner = findView(R.id.dis_banner);
        llOne = findView(R.id.ll_dis_one);
        llTwo = findView(R.id.ll_dis_two);
        llThree = findView(R.id.ll_dis_three);
        tvCollection = findView(R.id.tv_dis_one);
        tvExecution = findView(R.id.tv_dis_two);
        tvOver = findView(R.id.tv_dis_three);
        oneLine = findView(R.id.v_one_line);
        twoLine = findView(R.id.v_two_line);
        threeLine = findView(R.id.v_three_line);
        mPager = findView(R.id.vp_volunteer);

        tvCurCity.setOnClickListener(this);
        tvVolunteer.setOnClickListener(this);
        llOne.setOnClickListener(this);
        llTwo.setOnClickListener(this);
        llThree.setOnClickListener(this);
    }


    public void getDisBanners() {
        if (NetWorkUtils.isNetAvailable(mContext)) {
            request = new BasicRequest(AddressManager.getInstance().getAddress());
            DiscoveryParameters parameters = new DiscoveryParameters();
            parameters.setCommand(mContext.getString(R.string.command_getBanners));
            parameters.setUserId(MyApplication.getInstance().getAccount());
            parameters.setType(mContext.getString(R.string.two));
            request.add(mContext.getString(R.string.command), parameters.getCommand());
            request.add(mContext.getString(R.string.platform), parameters.getPlatform());
            request.add(mContext.getString(R.string.data), new Gson().toJson(parameters));
            request.setCancelSign(toString());
            WebServerManager.getInstance().add(mContext, request, this,
                    DIS_BANNER_LIST_WHAT, true, true, true);
        } else {
            ToastUtils.showShort(mContext.getString(R.string.network_error));
        }
    }


    @Override
    public int bindLayoutId() {
        return R.layout.fragment_discovery;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.tv_dis_location:
                // 推荐地点列表
                CityListActivity.start(this, CITY_LIST_REQUEST_CODE);
                break;

            case R.id.tv_dis_volunteer:
                // 我的志愿
                VolunteerActivity.start(mContext);
                break;

            case R.id.ll_dis_one:
                mPager.setCurrentItem(0, false);
                break;

            case R.id.ll_dis_two:
                mPager.setCurrentItem(1, false);
                break;

            case R.id.ll_dis_three:
                mPager.setCurrentItem(2, false);
                break;

            default:
                break;

        }
    }

    private void setTvColor(int one, int two, int three) {
        tvCollection.setTextColor(ContextCompat.getColor(mContext, one));
        tvExecution.setTextColor(ContextCompat.getColor(mContext, two));
        tvOver.setTextColor(ContextCompat.getColor(mContext, three));
    }

    private void setLine(int one, int two, int three) {
        oneLine.setVisibility(one);
        twoLine.setVisibility(two);
        threeLine.setVisibility(three);
    }

    private void initViewPager() {
        collectionFrag = new CollectionFrag(application.getString(R.string.dis_flag));
        executionFrag = new ExecutionFrag(application.getString(R.string.dis_flag));
        overFrag = new OverFrag(application.getString(R.string.dis_flag));
        fragments.add(collectionFrag);
        fragments.add(executionFrag);
        fragments.add(overFrag);
//        mPager.setOffscreenPageLimit(2);
        mPager.setCurrentItem(0, false);
        mPager.setAdapter(new DisPagerAdapter());
        mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                switch (position) {

                    case 0:
                        setTvColor(R.color.colorThirdPrimary, R.color.black_x, R.color.black_x);
                        setLine(View.VISIBLE, View.INVISIBLE, View.INVISIBLE);
                        tvCurCity.setVisibility(View.VISIBLE);
                        break;

                    case 1:
                        setTvColor(R.color.black_x, R.color.colorThirdPrimary, R.color.black_x);
                        setLine(View.INVISIBLE, View.VISIBLE, View.INVISIBLE);
                        tvCurCity.setVisibility(View.GONE);
                        break;

                    case 2:
                        setTvColor(R.color.black_x, R.color.black_x, R.color.colorThirdPrimary);
                        setLine(View.INVISIBLE, View.INVISIBLE, View.VISIBLE);
                        tvCurCity.setVisibility(View.GONE);
                        break;

                    default:
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private class DisPagerAdapter extends FragmentStatePagerAdapter {

        public DisPagerAdapter() {
            super(mContext.getSupportFragmentManager());
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

    }

    private void andPermission() {
        // 需要调用AndPermission来开启定位权限提示
        AndPermission.with(this)
                .requestCode(100)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .callback(listener)
                // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                // 这样避免用户勾选不再提示，导致以后无法申请权限。
                // 你也可以不设置。
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale)
                                .show();
                    }
                })
                .start();
    }

    // 权限回调监听
    PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == 100) {
                // 表示定位的权限申请通过
                createLocationRequest();
            }

        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if (requestCode == 100) {
                // 即使是用户选择了不在询问还是会toast该提示语
                ToastUtils.showShort("请开启你的定位权限");
            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(mContext, 404).show();

            }

        }
    };

    protected void createLocationRequest() {

        tvCurCity.setText("定位中...");

        // 初始化请求
        locationRequest = new AMapLocationClient(mContext.getApplicationContext());

        // 设置回调监听
        locationRequest.setLocationListener(this);

        // 初始化参数集
        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();

        // 高精度定位模式，省电模式， 仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);

        // 是否返回地址信息
        mLocationOption.setNeedAddress(true);

        // 设置重定位时间间隔
        mLocationOption.setInterval(5000);

        mLocationOption.setOnceLocation(true);

        // 设置参数集
        locationRequest.setLocationOption(mLocationOption);

        locationRequest.startLocation();
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation == null || aMapLocation.getErrorCode() != 0) {
            Logger.e("Amap location Error");
            ToastUtils.showShort("定位失败");
            return;
        }

        Logger.i("Current user postion is lat : " + aMapLocation.getLatitude() +
                " and lon : " + aMapLocation.getLongitude());
        mLatitude = aMapLocation.getLatitude();
        mLongitude = aMapLocation.getLongitude();
        CURRENT_CITY = aMapLocation.getCity();
        tvCurCity.setText(aMapLocation.getCity()+"");
        if (!TextUtils.isEmpty(CURRENT_CITY)){
            EventBus.getDefault().post(new BaseEvent(application.getString(R.string.discovery_location_sc)));
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        switch (requestCode) {

            case 404:
                ToastUtils.showShort("开启定位权限回来");
                break;

            case CITY_LIST_REQUEST_CODE:
                if (null != data) {
                    String city = data.getStringExtra(CityListActivity.KEY_PICKED_CITY);
                    if (!TextUtils.isEmpty(city)) {
                        CURRENT_CITY = city;
                        tvCurCity.setText(city);
                        if (!TextUtils.isEmpty(CURRENT_CITY)){
                            EventBus.getDefault().post(new BaseEvent(application.getString(R.string.discovery_location_sc)));
                        }
                    }
                }
                break;

            default:
                break;

        }
    }

    @Override
    public void onSucceed(int what, Response<BasicBean> response) {
        BasicBean basicBean = response.get();
        if (basicBean == null) return;

        if (basicBean.isSuccess()){
            if (what == DIS_BANNER_LIST_WHAT){
                DiscoveryData discoveryData = basicBean.parseData(DiscoveryData.class);
                if (discoveryData == null) return;
                initBanner(discoveryData.getBannerses());
            }else {
                return;
            }
        } else {
            ToastUtils.showShort(basicBean.getMsg());
        }
    }

    private void initBanner(final List<AppBanner> banners) {
        if (banners.isEmpty()) {
            return;
        }

        bannerImages.clear();
        for (AppBanner banner : banners) {
            bannerImages.add(banner.getPicUrl());
        }

        if (bannerImages.size() > 1) {
            mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            mBanner.setIndicatorGravity(BannerConfig.CENTER);
            mBanner.isAutoPlay(true);
        } else {
            mBanner.setIndicatorGravity(BannerConfig.NOT_INDICATOR);
            mBanner.setViewPagerIsScroll(false);
            mBanner.isAutoPlay(false);
        }
        mBanner.setImages(bannerImages).setImageLoader(new GlideImageLoader()).start();
        mBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                AppBanner banner = banners.get(position);
                if (TextUtils.equals(banner.getActiveState(), application.getString(R.string.one))) {
                    WebDetailActivity.start(mContext, getString(R.string.app_banner), banner.getActiveUrl());
                }
            }
        });
    }


    @Override
    public void onPause() {
        super.onPause();
        if (locationRequest != null) {
            locationRequest.stopLocation();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (locationRequest != null) {
            locationRequest.stopLocation();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (locationRequest != null) {
            locationRequest.onDestroy();
        }
    }
}
